<!--
 * @Description:
 * @version:
 * @Author: sunqian_sr
 * @Date: 2022-11-29 16:36:58
 * @LastEditors: Andy
 * @LastEditTime: 2023-03-28 15:21:17
-->
<template>
  <x-dialog
    :title="title"
    :show.sync="visible"
    v-if="visible"
    :submitLoading="btnLoading"
    :before-close="handleClose"
    width="70%"
    @onCancel="handleClose"
    @onSubmit="handleSubmit"
  >
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="基本信息" name="first"></el-tab-pane>
      <el-tab-pane label="岗位信息" name="second"></el-tab-pane>
    </el-tabs>
    <el-form
      v-show="activeName === 'first'"
      :model="params"
      class="demo-form-inline"
      ref="params"
      :rules="rules"
      label-position="top"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="$t('system.user.userName')" prop="username">
            <el-input v-model="params.username" :placeholder="$t('system.user.up')" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('system.user.name')" prop="realName">
            <el-input v-model="params.realName" :placeholder="$t('system.user.np')" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('system.user.nickName')" prop="nickName">
            <el-input v-model="params.nickName" :placeholder="$t('system.user.np2')" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('system.user.gender')" prop="gender">
            <x-radio-group :list-data="dictOptions['upms_user.gender']" v-model="params.gender"></x-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('system.user.userType')" prop="userType">
            <x-select
              :placeholder="$t('system.user.userTypePlaceholder')"
              v-model="params.userType"
              :options="dictOptions['upms_user.user_type']"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="!params.id">
          <el-form-item :label="$t('system.user.password')" prop="password">
            <el-input
              show-password
              type="password"
              v-model="params.password"
              :placeholder="$t('system.user.passwordTxt')"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('system.user.phoneNumber')" prop="mobile">
            <el-input v-model="params.mobile" :placeholder="$t('system.user.input')" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('system.user.email')" prop="email">
            <el-input v-model="params.email" :placeholder="$t('system.user.emailTxt')" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('system.user.jobNumber')" prop="employeeId">
            <el-input v-model="params.employeeId" :placeholder="$t('system.user.jobInput')" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('system.user.rank')" prop="rankId">
            <x-select-tree
              v-model="params.rankId"
              :options="rankTreeOptions"
              :defaultProps="defaultRankProps"
              :placeholder="$t('system.user.rankSelect')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('system.user.statusJob')" prop="workStatus">
            <x-select
              :placeholder="$t('system.user.statusJobSelect')"
              v-model="params.workStatus"
              :options="dictOptions['upms_user.work_status']"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item :label="$t('system.user.onlineStatus')" prop="onlineStatus">
            <x-radio-group :list-data="dictOptison.online" v-model="params.onlineStatus"></x-radio-group>
          </el-form-item>
        </el-col> -->
        <el-col :span="12">
          <el-form-item :label="$t('system.user.status')" prop="state">
            <!-- <x-select :placeholder="$t('system.user.choose')"
                        v-model="params.state"
                        :options="dictOptison.state"
                        style="width: 100%;"/> -->
            <x-radio-group :list-data="dictOptions['system.state']" v-model="params.state"></x-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-col :span="24">
        <el-form-item :label="$t('system.user.note')" prop="remark">
          <el-input type="textarea" v-model="params.remark" style="width: 100%"></el-input>
        </el-form-item>
      </el-col>
    </el-form>
    <user-Info ref="userInfoCom" v-show="activeName === 'second'" :user-info="params"></user-Info>
  </x-dialog>
</template>
<script>
  import { encrypt, omit, throttle, checkPwd, checkEmail, checkUserName, checkMobilePhone } from '@package/utils'
  import { apiPostAddUserBase, apiPostEditUserBase } from '../api'
  import { apiPostRankTree } from '../../organization/api/rank'
  import UserInfo from './userInfo.vue'
  import { EnumApiCode } from '../../../../../../globalEnum'
  // import { dictOptison } from '../config/userConfig'
  export default {
    components: { UserInfo },
    props: {
      dictOptions: {
        type: Object,
        default: () => ({})
      }
    },
    data() {
      return {
        visible: false,
        title: '',
        params: {
          username: '',
          password: '',
          realName: '',
          gender: '1',
          userType: '',
          mobile: '',
          employeeId: '',
          email: '',
          rankId: '',
          remark: '',
          workStatus: '',
          onlineStatus: '1',
          state: '1',
          mainPost: null,
          deputyPosts: []
          // tenantId: 0
        },
        rules: {
          username: [
            { required: true, message: this.$t('system.user.userPlaceholder'), trigger: 'blur' },
            { min: 1, max: 100, message: this.$t('system.user.userLengthPlaceholder'), trigger: 'blur' }
            // { validator: this.validateUserName, trigger: 'blur' }
          ],
          realName: [
            { required: true, message: this.$t('system.user.np'), trigger: 'blur' },
            { min: 1, max: 20, message: this.$t('system.user.userLengthPlaceholder'), trigger: 'blur' },
            { validator: this.validateName, trigger: 'blur' }
          ],
          password: [
            { required: true, message: this.$t('system.user.enterPassword'), trigger: 'blur' },
            { min: 6, max: 50, message: this.$t('system.user.pwdLengthPlaceholder'), trigger: 'blur' },
            { validator: this.validatePwd, trigger: 'blur' }
          ],
          mobile: [
            { required: true, message: this.$t('system.user.enterPassword'), trigger: 'blur' },
            { validator: this.validatePhone, trigger: 'blur' }
          ],
          email: [
            { required: true, message: this.$t('system.user.emailTxt'), trigger: 'blur' },
            { validator: this.validateEmail, trigger: 'blur' }
          ],
          rankId: [
            // {required: true, message: this.$t('system.user.rankSelect'), trigger: 'blur'}
          ],
          userType: [{ required: true, message: this.$t('system.user.userTypePlaceholder'), trigger: 'blur' }],
          state: [{ required: true, message: this.$t('system.user.choose'), trigger: 'blur' }],
          workStatus: [{ required: true, message: this.$t('system.user.statusJobSelect'), trigger: 'blur' }],
          onlineStatus: [{ required: true, message: this.$t('system.user.onlineStatusSelect'), trigger: 'blur' }]
        },
        rankTreeOptions: [],
        defaultRankProps: {
          label: 'shortName',
          value: 'id',
          children: 'children'
        },
        btnLoading: false,
        activeName: 'first'
      }
    },
    created() {
      this.loadRankTree()
    },
    methods: {
      handleOpen(info) {
        this.visible = true
        if (info?.id) {
          this.title = this.$t('system.user.edit')
          this.$nextTick(() => {
            this.params = JSON.parse(JSON.stringify(info))
            this.params.userType += ''
            this.params.state += ''
            this.params.gender = `${this.params.gender}` || '1'
            this.params.onlineStatus += ''
            this.params.workStatus = this.params.workStatus ? `${this.params.workStatus}` : '1'
          })
        } else {
          this.title = this.$t('system.user.add')
        }
      },
      async loadRankTree() {
        const { data, code } = await apiPostRankTree()
        if (code === EnumApiCode.Success) {
          this.rankTreeOptions = data
        }
      },
      handleClick(tab) {
        this.activeName = tab.name
      },
      handleClose() {
        this.$refs.params.resetFields()
        this.params = omit(this.params, 'id')
        // this.$data.params = JSON.parse(JSON.stringify(this.$options.data().params))
        this.params.mainPost = {}
        this.params.deputyPosts = []
        this.activeName = 'first'
        this.btnLoading = false
        this.visible = false
      },
      handleSubmit: throttle(function () {
        this.btnLoading = true
        this.$refs.params.validate(
          async (valid) => {
            if (valid) {
              const mPost =
                this.$refs.userInfoCom && this.$refs.userInfoCom.checkedMainPost.length
                  ? this.$refs.userInfoCom.checkedMainPost[0]
                  : this.params.mainPost
              if (mPost?.id) {
                mPost.postId = mPost.id
                delete mPost.id
              }
              const dPost =
                this.$refs.userInfoCom && this.$refs.userInfoCom.checkedSubPost.length
                  ? this.$refs.userInfoCom.checkedSubPost
                  : this.params.deputyPosts
              const param = {
                ...this.params,
                mainPost: mPost,
                deputyPosts: dPost.map((v) => {
                  return {
                    postId: v.id,
                    ...omit(v, 'id')
                  }
                }),
                password: encrypt(this.params.password)
              }
              try {
                const { code, msg } =
                  'id' in this.params
                    ? await apiPostEditUserBase(omit(param, 'password'))
                    : await apiPostAddUserBase(param)
                if (code === EnumApiCode.Success) {
                  // this.$refs.params.resetFields()
                  this.$message.success(
                    'id' in this.params ? this.$t('system.user.editSuccess') : this.$t('system.user.newSuccess')
                  )
                  this.$emit('handleSuccess')
                  // this.handleClose()
                  this.visible = false
                } else {
                  this.$message.error(msg)
                }

                this.btnLoading = false
              } catch (e) {
                this.btnLoading = false
              }
            } else {
              this.$message.error('请完善基本信息')
              this.btnLoading = false
              return false
            }
          },
          () => {
            this.btnLoading = false
          }
        )
      }, 1000),
      validateUserName(rule, value, callback) {
        if (value && value !== '' && !checkUserName(value)) {
          callback(new Error(this.$t('system.user.userNameTips')))
        } else {
          callback()
        }
      },
      validateName(rule, value, callback) {
        value = value.replace(/\s*/g, '')
        if (value.length === 0) {
          callback(new Error(this.$t('system.user.np')))
        } else {
          callback()
        }
      },
      validatePwd(rule, value, callback) {
        if (value && value !== '' && !checkPwd(value)) {
          callback(new Error(this.$t('system.user.PasswordMode')))
        } else {
          callback()
        }
      },
      validateEmail(rule, value, callback) {
        if (value && value !== '' && !checkEmail(value)) {
          callback(new Error(this.$t('system.user.EmailAddresses')))
        } else {
          callback()
        }
      },
      validatePhone(rule, value, callback) {
        if (value && value !== '' && !checkMobilePhone(value)) {
          callback(new Error(this.$t('system.user.PleasePhoneRight')))
        } else {
          callback()
        }
      }
    }
  }
</script>
